<template>
  <view>
    <u-modal title="下载指引" v-model="visible" ref="uModal" show-cancel-button confirm-text="确认下载"
             @confirm="toShowMyDownloadTime()"
    >
      <view style="margin: 16px">

        <view>
                  <span>为保障每位伙伴下载素材的原创性，每条素材只能下载1次。多次下载需点击<span
                      @click.stop="applyDownload"
                      style="text-decoration: underline;color: green;">申请下载</span></span>
        </view>
        <view style="margin-top: 15px;color: red;">
          <span>注意：视频文案可通过个人中心的下载历史中进行查看</span>
        </view>
      </view>
    </u-modal>

    <toDownloadApplyModal ref="toDownloadApplyModal"></toDownloadApplyModal>

    <u-modal v-model="showMyDownloadTime" confirm-text="关闭" title="使用次数" ref="uModalApplyTime">
      <u-modal v-model="showContentModal" title="文案/挂车链接" @confirm="contentClose">


        <!--        文案<view style="padding: 8px">{{ showContent }}</view>-->
        <!--        <span style="margin-left: 10px;color: green"-->
        <!--              @click="copyThis(showContent)">复制</span>-->
        <!--        挂车链接<view style="padding: 8px">{{ trailerLink }}</view>-->
        <!--        <span style="margin-left: 10px;color: green"-->
        <!--              @click="copyThis(trailerLink)">复制</span>-->

        <u-form ref="uForm">
          <u-form-item label="文案" prop="name">
            <span>{{ showContent }}</span>
            <span style="margin-left: 10px;color: green" v-if="showContent"
                  @click="copyThis(showContent)">复制</span>
          </u-form-item>
          <u-form-item label="挂车链接" prop="intro">
            <span>{{ trailerLink }}</span>
            <span style="margin-left: 10px;color: green" v-if="trailerLink"
                  @click="copyThis(trailerLink)">复制</span>
          </u-form-item>
        </u-form>

      </u-modal>
      <u-line-progress :striped="true" :percent="percent" :striped-active="true"
                       v-show="showDownloadingLoading"></u-line-progress>
      <span style="color: green;margin-left: 10px">注：点击"可用次数"下载</span>
      <u-tabs :list="tabsList"
              :current="tabsCurrent"
              :is-scroll="false"
              @click="tabsClick"
              @change="tabsChange"
              :show-bar="false"></u-tabs>


      <view>
        <scroll-view scroll-y="true" @scrolltolower="onScrollToLower">
          <view v-if="dowLoadTimeList.length>0" style="height: 311px">
            <uni-list :border="true" v-for="(item,index) in dowLoadTimeList" :key="index">
              <uni-list-item link @click="verifyTrendsDownload(item.walkTrendsDownloadNum.id)">
                <template v-slot:header>
                  <span v-if="item.pmsGoods">{{ item.pmsGoods.title }}</span>
                  <span v-else>所有商品</span>
                </template>
                <template v-slot:footer style="margin-left: 20px;">
                  <view style="display:flex;flex-wrap : nowrap">
                    <view v-if="item.walkTrendsDownloadNum.source===2">申请次数:{{
                        item.walkTrendsDownloadNum.num
                      }}
                    </view>
                    <view v-if="item.walkTrendsDownloadNum.source===1">赠送次数:{{
                        item.walkTrendsDownloadNum.num
                      }}
                    </view>
                    <view v-if="item.walkTrendsDownloadNum.status===1" style="color: green;text-decoration:underline;">
                      可用次数:{{
                        item.walkTrendsDownloadNum.useNum
                      }}
                    </view>
                  </view>

                </template>
              </uni-list-item>
            </uni-list>
            <uni-load-more :showIcon="true" :showText="true" :status="loadStatus"
                           v-if="dowLoadTimeList.length>0&&isShowLoadMore"></uni-load-more>
          </view>
        </scroll-view>
        <no-data :list="dowLoadTimeList"></no-data>
      </view>


    </u-modal>

    <u-modal title="保存指引" v-model="visibleStep" ref="uModalStep" :show-confirm-button="isShowConfirmButton"
             :show-cancel-button="false" confirm-text="前往保存"
             @confirm="afterStepToSave()">
      <view style="margin-top: 10px">
          <span
              @click="skipStep"
              style="text-decoration: underline;color: green;margin-left: 41%">跳过指引</span>
      </view>

      <view style="margin-top: 10px">
        <u-steps :list="numList" :current="currentStep"></u-steps>
        <view style="display: flex;justify-content: center;align-items: center;flex-direction: row;">
          <u-button @click="preStep" type="primary" size="mini" v-if="showPreStep">上一步</u-button>
          <u-button @click="nextStep" type="primary" size="mini" v-if="showNextStep" style="margin-left: 20px">下一步
          </u-button>
        </view>

      </view>


      <u-image mode="widthFix" width="100%" height="700rpx" :src="stepImage"></u-image>


    </u-modal>


  </view>

</template>

<script>
import toDownloadApplyModal from "@/pages/common/toDownloadApply.vue";

const $ = require('../../../utils/api.js');
const API = require('../../../utils/api/find.js').default;
export default {
  components: {toDownloadApplyModal},
  name: "downloadVideo",
  props: {
    shopId: {
      required: Number
    },
    type: {
      type: Number,
      default: 1
    },
    trailerLink: {
      type: String,
      default: ""
    },
    goodsId: {
      default: '',
    },
  },
  data() {
    return {
      isShowLoadMore: true,
      trendsId: "",
      pageSize: 10,
      trendsInfo: {},
      tabsCurrent: 0,
      currentDownloadNumId: "",
      percent: 0,
      isLoading: false,  //是否加载中
      loadStatus: "",   //uni-load-more的状态
      isBottomReached: false,
      showPreStep: false,
      showNextStep: false,
      currentHref: "",
      isShowConfirmButton: false,
      stepImage: "https://img.fscmkjznb.com/static/step1.png",
      currentStep: 0,
      numList: [{
        name: '第一步'
      }, {
        name: '第二步'
      }, {
        name: '第三步'
      }, {
        name: '第四步'
      },],
      showContentModal: false,
      showContent: "",
      visibleStep: false,
      page: 1,
      totalPage: 0,
      tabsList: [],
      showDownloadingLoading: true,
      showMyDownloadTime: false,
      dowLoadTimeList: [],
      isXcx: false,
      visible: false,
      videoInfo: null,
    }
  },
  methods: {
    contentClose() {
      this.showMyDownloadTime = false
      $.go("/pagesA/shops/detail?id=" + this.trendsGoodsInfo.goodsId + "&shopId=" + this.shopId)
    },
    toDownload(downloadNumId) {
      if (this.percent > 0 && this.percent < 100) {
        uni.showToast({
          title: "请等待当前下载进度结束再操作",
          icon: "none"
        });
        return
      }
      this.visible = false
      const self = this;

      let info = self.trendsInfo;
      let url = ""
      if (self.type === 1) {
        url = info.videoUrl
      } else if (self.type === 3) {
        url = info.images
      }


      const downloadTask = uni.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: "视频连接正确",
              icon: "none"
            });
            if (!self.isXcx) {
              this.currentDownloadNumId = downloadNumId
              //如果是H5 那么弹出下载步骤
              self.currentHref = res.tempFilePath
              self.visibleStep = true
              self.currentStep = 0
              self.isShowConfirmButton = false
              self.showPreStep = false
              self.showNextStep = true
            }


            if (self.isXcx) {
              if (this.type === 1) {
                uni.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function () {

                    self.trendsInfo = info;
                    uni.showToast({
                      title: "保存成功",
                      icon: "none"
                    });
                    self.addTrendsDownloadLog(self.trendsInfo, downloadNumId, self.type)
                  },
                  fail: function (e) {

                    self.trendsInfo = info;
                    console.log(e)
                    uni.showToast({
                      title: "保存失败，请稍后重试:" + e.errMsg,
                      icon: "none"
                    });
                    self.percent = 0
                  }
                });
              } else if (this.type === 3) {
                uni.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success: function () {

                    self.trendsInfo = info;
                    uni.showToast({
                      title: "保存成功",
                      icon: "none"
                    });
                    self.addTrendsDownloadLog(self.trendsInfo, downloadNumId, self.type)

                  },
                  fail: function (e) {

                    self.trendsInfo = info;
                    console.log(e)
                    uni.showToast({
                      title: "保存失败，请稍后重试",
                      icon: "none"
                    });
                    self.percent = 0
                  }
                });
              }
            }
          }
        }
      });

      downloadTask.onProgressUpdate((res) => {
        self.percent = 0
        self.showDownloadingLoading = true
        self.trendsInfo = info;
        self.percent = res.progress

      });
    },
    addTrendsDownloadLog(data, downloadNumId, type) {
      let self = this
      console.log("data", data)
      $.ajax({
        url: API.addTrendsDownloadLog,
        data: {
          "publishGoodsId": self.trendsGoodsInfo.goodsId,
          "publishWalkMemberId": data.walkMemberId,
          "publishWalkMemberName": data.walkMemberName,
          "publishWalkMemberHeadImg": data.walkMemberHeadImg,
          "trendsId": data.id,
          "videoUrl": data.type === 1 ? data.videoUrl : "",
          "imgUrl": data.type === 3 ? data.images : "",
          "type": data.type,
          "content": data.content,
          "downloadNumId": downloadNumId,
        },
        method: 'POST',
        success(res) {
          $.$toast('已生成下载记录');
          //下载成功后将这个视频标记为有所属
          self.$emit('changeBelongMemberId');
          //如果是H5 就直接保存的本地临时文件
          //显示文案窗口
          self.showContentModal = true
          self.showContent = data.content
          let arr = self.dowLoadTimeList

          for (let i = 0; i < arr.length; i++) {
            if (arr[i].walkTrendsDownloadNum.id === downloadNumId) {
              // 获取到目标对象
              var objToModify = arr[i].walkTrendsDownloadNum;
              // 进行相应的修改操作（这里只是为了演示）
              objToModify.useNum = objToModify.useNum - 1;
              // 将修改后的对象重新赋值给原数组中的对应位置
              arr[i].walkTrendsDownloadNum = objToModify;
              break; // 找到目标对象后就结束遍历
            }
          }

          //重新加载列表
          if (data.type === 1) {
            self.$emit("reloadListVideo")
          } else {
            self.$emit("reloadListImg")
          }

        }
      })
    },
    preStep() {
      if (this.currentStep > 0) {
        this.currentStep--
      }
      if (this.currentStep === 0) {
        this.showPreStep = false
        this.showNextStep = true
      } else if (this.currentStep === 3) {
        this.showPreStep = true
        this.showNextStep = false
      } else {
        this.showPreStep = true
        this.showNextStep = true
      }
      if (this.currentStep === 0) {
        this.stepImage = "https://img.fscmkjznb.com/static/step1.png"
      } else if (this.currentStep === 1) {
        this.stepImage = "https://img.fscmkjznb.com/static/step2.png"
      } else if (this.currentStep === 2) {
        this.stepImage = "https://img.fscmkjznb.com/static/step3.png"
      } else if (this.currentStep === 3) {
        this.stepImage = "https://img.fscmkjznb.com/static/step4.png"
      }
    },
    nextStep() {
      if (this.currentStep < 3) {
        this.currentStep++
      }
      if (this.currentStep === 0) {
        this.showPreStep = false
        this.showNextStep = true
      } else if (this.currentStep === 3) {
        this.showPreStep = true
        this.showNextStep = false
      } else {
        this.showPreStep = true
        this.showNextStep = true
      }
      if (this.currentStep === 0) {
        this.stepImage = "https://img.fscmkjznb.com/static/step1.png"
      } else if (this.currentStep === 1) {
        this.stepImage = "https://img.fscmkjznb.com/static/step2.png"
      } else if (this.currentStep === 2) {
        this.stepImage = "https://img.fscmkjznb.com/static/step3.png"
      } else if (this.currentStep === 3) {
        this.stepImage = "https://img.fscmkjznb.com/static/step4.png"
        this.isShowConfirmButton = true
      }
    },
    afterStepToSave() {
      //扣减次数，添加下载记录
      this.addTrendsDownloadLog(this.trendsInfo, this.currentDownloadNumId, 1)
      var oA = document.createElement("a");
      oA.download = '素材'; // 设置下载的文件名，默认是'下载'
      oA.href = this.currentHref; //临时路径再保存到本地
      document.body.appendChild(oA);
      oA.click();
      oA.remove(); // 下载之后把创建的元素删除

    },
    skipStep() {
      this.visibleStep = false
      this.afterStepToSave()
    },
    verifyTrendsDownload(id) {
      const self = this
      $.ajax({
        url: API.verifyTrendsDownload,
        data: {
          "id": id,
          "goodsId": self.goodsId,
          "trendsId": self.trendsId
        },
        loading: true,
        method: 'GET',
        success(res) {
          self.toDownload(id)
        }
      })
    },

    copyThis(data) {
      this.copy(data)
    },
    onScrollToLower() {
      this.isBottomReached = true;
      this.refreshData()
    },
    refreshData() {
      if (this.page < this.totalPage) {
        if (!this.isLoading) {  //此处判断，上锁，防止重复请求
          this.isLoading = true;
          this.page += 1;
          this.loadStatus = "loading";
          this.getListMyDownloadTime(this.type);
        }
      }
    },
    toShowDownloadModal(trendsId) {
      this.getTrendsInfo(trendsId);
      this.trendsId = trendsId
      this.visible = true
    },
    applyDownload() {
      this.$refs.toDownloadApplyModal.init();
    },
    toShowMyDownloadTime() {
      /*#ifdef MP-WEIXIN*/
      this.isXcx = true
      /*#endif*/
      /*#ifdef H5*/
      this.isXcx = false
      /*#endif*/
      this.dowLoadTimeList = []
      this.showMyDownloadTime = true
      this.showDownloadingLoading = false
      this.page = 1
      this.getListMyDownloadTime(this.type)
    },
    getListMyDownloadTime(type) {
      const self = this;
      $.ajax({
        url: API.getVerifyTrendsDownloadNumListToUse,
        data: {
          goodsId: self.goodsId,
          type: type,
          page: self.page,
          pageSize: self.pageSize
        },
        loading: true,
        method: 'GET',
        success(res) {
          res.data.list.forEach(item => {
            self.dowLoadTimeList.push(item)
          })

          self.totalPage = res.data.totalPage
          self.isLoading = false;
          let pageNum = res.data.pageNum;
          if (pageNum == self.totalPage) {
            self.isShowLoadMore = false
            self.loadStatus = ''
          } else {
            self.isShowLoadMore = true
            self.loadStatus = 'loadmore'
          }

        }
      })
    },
    getTrendsInfo(trendsId) {
      const self = this;
      $.ajax({
        url: API.findDetail,
        data: {
          trendsId: trendsId
        },
        loading: true,
        method: 'GET',
        success(res) {
          self.trendsInfo = res.data.walkTrends
          self.trendsGoodsInfo = res.data.trendsGoodsList[0]
        }
      })
    },
  }
}
</script>

<style scoped>

</style>
